package com.fitso.model.dao.aop;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.util.Assert;

import com.fitso.model.bean.User;
import com.fitso.model.dao.UserDao;

/**
 * Validating aspect for different {@link UserDao}s. This is the first check to
 * prevent data manipulations from happening and/or throwing their own
 * exceptions. This is to check data integrity not business rules. So while
 * blooper#google.com is an invalid email address it is perfectly valid for the
 * data store
 * 
 * @author timothystorm
 */

@Aspect
public class UserDataIntegrityAspect {
	/**
	 * Validates that the absolute minimum required fields have a value: user,
	 * user.email, user.password.
	 * 
	 * @param user
	 */
	@Before("execution(* com.fitso.model.dao.*.saveOrUpdate(..)) && args(user)")
	public void validateSaveOrUpdate(User user) {
		Assert.notNull(user, "user is a required parameter");
		Assert.isTrue(!StringUtils.isBlank(user.getEmail()), "email is a required attribute");
		Assert.isTrue(!StringUtils.isBlank(user.getPassword()), "password is a required attribute");
	}

	/**
	 * Validates that the fields used to identify a user is persisted are set
	 * and the delete has a reasonable chance of success.
	 * 
	 * @param user
	 */
	@Before("execution(* com.fitso.model.dao.*.delete(..)) && args(user)")
	public void validateDelete(User user) {
		Assert.notNull(user, "user is a required parameter");
		Assert.state(user.getId() != null && user.getId() >= 0, "user id not valid or in a persistent state");
	}
}
